package com.ruoyi.media.task;

import com.ruoyi.media.domain.MediaUser;
import com.ruoyi.media.service.IMediaUserService;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 广电用户数据同步定时任务
 * 每5分钟从CSV文件读取100条数据存入数据库
 */
@Component
public class MediaUserSyncTask {

    private static final Logger logger = LoggerFactory.getLogger(MediaUserSyncTask.class);
    
    @Autowired
    private IMediaUserService mediaUserService;
    
    // 当前读取位置
    private AtomicInteger currentPosition = new AtomicInteger(0);
    
    // CSV文件路径
    private final String csvFilePath = "c:/Users/Administrator/RuoYi-Vue01/python_project/media_users_wide_table.csv";
    
    /**
     * 定时同步任务
     * 每5分钟执行一次
     */
    @Scheduled(cron = "0 */5 * * * ?")
    public void syncMediaUserFromCsv() {
        logger.info("开始执行广电用户数据同步任务，当前读取位置: {}", currentPosition.get());
        
        List<MediaUser> userList = new ArrayList<>();
        int recordsToRead = 100;
        int recordsRead = 0;
        
        try (Reader reader = new FileReader(csvFilePath);
             CSVParser csvParser = new CSVParser(reader, CSVFormat.DEFAULT.withFirstRecordAsHeader())) {
            
            // 跳过已读取的记录
            for (int i = 0; i < currentPosition.get(); i++) {
                if (csvParser.iterator().hasNext()) {
                    csvParser.iterator().next();
                } else {
                    // 到达文件末尾，重置位置
                    logger.info("已到达文件末尾，重置读取位置");
                    currentPosition.set(0);
                    break;
                }
            }
            
            // 读取指定数量的记录
            for (CSVRecord record : csvParser) {
                if (recordsRead >= recordsToRead) {
                    break;
                }
                
                MediaUser mediaUser = convertToMediaUser(record);
                if (mediaUser != null) {
                    userList.add(mediaUser);
                    recordsRead++;
                }
            }
            
            // 更新读取位置
            currentPosition.addAndGet(recordsRead);
            
            // 批量插入数据
            if (!userList.isEmpty()) {
                int insertCount = mediaUserService.batchInsertMediaUser(userList);
                logger.info("成功同步 {} 条广电用户数据到数据库", insertCount);
            } else {
                logger.info("本次未同步到数据");
            }
            
        } catch (IOException e) {
            logger.error("读取CSV文件时发生错误: {}", e.getMessage(), e);
        } catch (Exception e) {
            logger.error("同步广电用户数据时发生错误: {}", e.getMessage(), e);
        }
    }
    
    /**
     * 将CSV记录转换为MediaUser对象
     */
    private MediaUser convertToMediaUser(CSVRecord record) {
        try {
            MediaUser user = new MediaUser();
            
            // 设置基础字段
            user.setTerminalNo(record.get("terminal_no"));
            user.setPhoneNo(record.get("phone_no"));
            user.setSmName(record.get("sm_name"));
            user.setRunName(record.get("run_name"));
            user.setSmCode(record.get("sm_code"));
            user.setOwnerName(record.get("owner_name"));
            user.setOwnerCode(record.get("owner_code"));
            user.setRunTime(record.get("run_time"));
            user.setAddressoj(record.get("addressoj"));
            user.setEstateName(record.get("estate_name"));
            user.setOpenTime(record.get("open_time"));
            user.setForce(record.get("force"));
            
            // 设置标签字段
            user.setTvConsumeLevel(record.get("tv_consume_level"));
            user.setBroadbandConsumeLevel(record.get("broadband_consume_level"));
            user.setIsRetention(record.get("is_retention"));
            user.setBusinessBrand(record.get("business_brand"));
            user.setTvEntryLevel(record.get("tv_entry_level"));
            user.setBroadbandEntryLevel(record.get("broadband_entry_level"));
            user.setUserValueLevel(record.get("user_value_level"));
            
            return user;
        } catch (Exception e) {
            logger.warn("转换CSV记录时出错: {}", e.getMessage());
            return null;
        }
    }
    
    /**
     * 手动触发同步任务（用于测试）
     */
    public void triggerSyncTask() {
        syncMediaUserFromCsv();
    }
}